
const sqlite3 = require('sqlite3').verbose();
const path = require('path');

const formatObject = function (res) {
    let _data = {};
    for (const key in res) {
        if (res.hasOwnProperty(key)) {
            const _item = res[key];
            var _key = key.replace(/\_(\w)/g, function (all, letter) {
                return letter.toUpperCase();
            });
            _data[_key] = _item;
        }
    };
    return _data;
};
var formatArray = function (res) {
    var data = [];
    for (let i = 0; i < res.length; i++) {
        const element = res[i];
        var _data = formatObject(element);
        data.push(_data);
    };
    return data;
};

class _DB_ {
    constructor() {
        this.filePath = './local.sqlite3';
        this.root = path.resolve('./');
        this.fileFullPath = path.join(path.resolve('./'), this.filePath);
        this.db = new sqlite3.Database(this.filePath, function (err) { });
    }
    creat(sql) {
        return new Promise((resolve, rejected) => {
            this.db.run(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(res);
                };
            });
        });
    }
    update(sql) {
        return new Promise((resolve, rejected) => {
            this.db.run(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(res);
                };
            });
        });
    }
    find(sql) {
        return new Promise((resolve, rejected) => {
            this.db.all(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(formatArray(res));
                };
            });
        });
    }
    get(sql) {
        return new Promise((resolve, rejected) => {
            this.db.get(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(formatObject(res));
                };
            });
        });
    }
    delete(sql) {
        var sql = sql.replace(/\'/g, "\\'");
        return new Promise((resolve, rejected) => {
            this.db.run(sql, function (err, res) {
                if (err) {
                    rejected(err);
                } else {
                    resolve(res);
                };
            });
        });
    }
}

export default _DB_;

